<?php
/**
 * TinyMVC Addons - AjaxFileUploadActionController.class.php file
 *
 * @author Adrian Wieczorek <adi(at)tinymvc(dot)org>
 * @package Addons
 * @version $Id$
 *
 */

/**
 * action controller class for AjaxFileUpload addon
 * @package Addons
 */
class AjaxFileUploadActionController extends TinyMVCActionController {

	public function __construct(TinyMVCModelAndView $modelAndView, TinyMVCRequest $request, $defaultAction = 'uploadForm') {
		parent::__construct($modelAndView, $request, $defaultAction);

		define('UPLOAD_PATH',  realpath(dirname(__FILE__) . '/../../html/files'));
		define('UPLOAD_SCRIPT', 'index.php?act=upload');
		define('UPLOAD_MAX_FILES',  5);
	}

	public function uploadFormAction() {
		$this->model->add('maxFiles', UPLOAD_MAX_FILES);
		$this->model->add('uploadScript', UPLOAD_SCRIPT);

		$this->view->add('form', 'uploadForm.view');
	}

	public function uploadAction() {
		$token = $this->request->getParam('multiUploadFormToken');
		$handler = $this->request->getSessionParam('handler') ? $this->request->getSessionParam('handler') : null;

		if((($handler instanceof MultiUploadHandler) && ($handler->getToken() != $token)) || ($handler == null)) {
			// create new handler if token has changed or there's no session already
			$handler = new MultiUploadHandler($token, UPLOAD_PATH);
		}

		$this->model->add('result', $handler->handle($_FILES));
		$this->view->add('result', 'uploadResult.view');
	}

}
